import socket

import consul


# 获取本机IP
def get_local_ip():
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        s.connect(('8.8.8.8', 80))
        ip = s.getsockname()[0]
    finally:
        s.close()
    return ip


# 注册服务到Consul
def register_service(service_name, port):
    c = consul.Consul(host='127.0.0.1', port=8500)  # 替换为你的Consul地址
    local_ip = get_local_ip()

    check = consul.Check.http(
        f'http://{local_ip}:{port}/health',
        interval='10s',
        timeout='5s'
    )

    c.agent.service.register(
        service_name,
        service_id=f'{service_name}-{local_ip}-{port}',
        address=local_ip,
        port=port,
        check=check
    )
